//
//  WLHomeController.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/4/23.
//

import UIKit

class WLHomeController: ZsBaseViewController,UserMessageDelegate,ClientViewDelegate,ExpressViewDelegate,ClientEmptyDelegate {

    var clientDic:Dictionary<String, Any>!
    var tabBarClick:Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = ""
        self.view.backgroundColor = UIColor.init(hexString: "#F3F3F3")
        NotificationCenter.default.addObserver(self, selector: #selector(languageNotification), name: NSNotification.Name(rawValue: "languageNotification"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(tabBarClickNotification), name: NSNotification.Name(rawValue: "TabBarClick"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(notificationInfo), name: NSNotification.Name(rawValue: "jpushNotification"), object: nil)
        if WLUserModel.getUserType() == "1" {
            self.setUI()
        }
        HttpService.sharedHttpService().getSyncServerTimeSuccess { (json, state, error) in
            
        }
        
        let orderNo:String = UserDefaults.standard.string(forKey: ActionHeader.UserDefault_NotificationOrderNo) ?? ""
        if orderNo.count > 0 {
            UserDefaults.standard.setValue("", forKey: ActionHeader.UserDefault_NotificationOrderNo)
            let orderDetailC = OrderDetailController.init()
            let model = OrderListModel.init()
            model.orderSn = orderNo
            orderDetailC.orderModel = model
            self.currentViewController()?.navigationController?.pushViewController(orderDetailC, animated: true)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.tabBarClick {
            self.navigationController?.setNavigationBarHidden(true, animated: false)
            self.tabBarClick = false
        } else {
            self.navigationController?.setNavigationBarHidden(true, animated: true)
        }
        self.statusBarView.backgroundColor = UIColor.white
        
        let week:NSInteger = NSCalendar.current.ordinality(of: .weekday, in: .year, for: NSDate.init() as Date)!
        let weekValue = UserDefaults.standard.integer(forKey: WLUserModel.getPhone() + ActionHeader.WLMyanmarArea)
        if (weekValue == week ) {
            HttpService.sharedHttpService().getMyanmarAreaSuccess { (state) in
                if state {
                    UserDefaults.standard.setValue(week, forKey: WLUserModel.getPhone() + ActionHeader.WLMyanmarArea)
                }
            }
            HttpService.sharedHttpService().getGoodsTypeSuccess { (state) in
                
            }
        }
        //如果是客户登录每次进入界面去调取物流统计
        if WLUserModel.getUserType() == "2" {
            HttpService.sharedHttpService().getlogisticsStatisticsSuccess { (json, state, error) in
                if state {
                    let jsonData = json["data"].description.data(using: String.Encoding.utf8, allowLossyConversion: false)!
                    self.clientDic = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String:Any]
                }
                self.setUI()
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    @objc func languageNotification() {
        HttpService.sharedHttpService().getMyanmarAreaSuccess { (state) in
            if state {
                let week:NSInteger = NSCalendar.current.ordinality(of: .weekday, in: .year, for: NSDate.init() as Date)!
                UserDefaults.standard.setValue(week, forKey: WLUserModel.getPhone() + ActionHeader.WLMyanmarArea)
            }
        }
        HttpService.sharedHttpService().getGoodsTypeSuccess { (state) in
            
        }
    }
    
    @objc func tabBarClickNotification() {
        self.tabBarClick = true
    }
    
    @objc func notificationInfo(note:Notification) {
        let noteDict:Dictionary = note.object as! Dictionary<String, Any>
        UserDefaults.standard.setValue("", forKey: ActionHeader.UserDefault_NotificationOrderNo)
        let orderDetailC = OrderDetailController.init()
        let model = OrderListModel.init()
        model.orderSn = noteDict["orderSn"].debugDescription
        orderDetailC.orderModel = model
        self.currentViewController()?.navigationController?.pushViewController(orderDetailC, animated: true)
        
    }
    
    func setUI() {
        self.scrollView .removeFromSuperview()
        self.view.addSubview(self.scrollView)
        self.scrollView.addSubview(self.userView)
        self.scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view.snp.top).offset(Constants.is_iphoneX ? 45:20)
            make.left.equalTo(self.view.snp.left).offset(0)
            make.width.equalTo(self.view.snp.width)
            make.height.equalTo(self.view.snp.height)
        }
        self.userView.snp.makeConstraints { (make) in
            make.top.equalTo(self.scrollView.snp.top).offset(0)
            make.height.equalTo(305)
            make.width.equalTo(self.scrollView.snp.width)
        }
        let userRole = WLUserModel.getUserType()
        if userRole == "1" {
            self.scrollView.addSubview(self.expressView)
            self.expressView.snp.makeConstraints { (make) in
                make.top.equalTo(self.userView.snp.bottom).offset(20)
                make.left.equalTo(self.scrollView.snp.left).offset(0)
                make.height.equalTo(221)
                make.width.equalTo(self.scrollView.snp.width)
                make.bottom.equalTo(self.scrollView.snp.bottom).offset(-50)
            }
        } else {
            let nearlyThirtySend = Float(self.clientDic["nearlyThirtySend"].debugDescription) ?? 0
            let warehousing = Float(self.clientDic["warehousing"].debugDescription) ?? 0
            let todaySend = Float(self.clientDic["todaySend"].debugDescription) ?? 0
            let todayFreightAmount = Float(self.clientDic["todayFreightAmount"].debugDescription) ?? 0
            let todayReturn = Float(self.clientDic["todayReturn"].debugDescription) ?? 0
            let todayCollectionFreightAmount = Float(self.clientDic["todayCollectionFreightAmount"].debugDescription) ?? 0

            if nearlyThirtySend <= 0 && warehousing <= 0 &&
                todaySend <= 0 && todayFreightAmount <= 0 &&
                todayReturn <= 0 && todayCollectionFreightAmount <= 0{
                self.clientView.removeFromSuperview()
                self.clientView.isHidden = false
                self.scrollView.addSubview(self.clientEmptyView)
                self.clientEmptyView.snp.makeConstraints { (make) in
                    make.top.equalTo(self.userView.snp.bottom).offset(20)
                    make.left.equalTo(self.view.snp.left).offset(15)
                    make.right.equalTo(self.view.snp.right).offset(-15)
                    make.height.equalTo(173)
                    make.bottom.equalTo(self.scrollView.snp.bottom).offset(-50)
                }
            } else {
                self.clientEmptyView.removeFromSuperview()
                self.clientEmptyView.isHidden = false
                self.scrollView.addSubview(self.clientView)
                self.clientView.snp.makeConstraints { (make) in
                    make.top.equalTo(self.userView.snp.bottom).offset(20)
                    make.left.equalTo(self.scrollView.snp.left).offset(0)
                    make.width.equalTo(self.scrollView.snp.width)
                    make.bottom.equalTo(self.scrollView.snp.bottom).offset(-50)
                }
            }
        }
        
    }
    
    func homeViewAcrionDelegate(actonType:HomeViewActonType) {
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.view.endEditing(true)
    }
    
    lazy var userView:UserMessageView = {
        let userView:UserMessageView = Bundle.main.loadNibNamed("UserMessageView", owner: self, options: nil)?.first as! UserMessageView
        userView.delegate = self
        return userView
    }()
    
    lazy var clientView:ClientView = {
        let clientView:ClientView = Bundle.main.loadNibNamed("ClientView", owner: self, options: nil)?.first as! ClientView
        clientView.delegate = self
        clientView.clientDic = self.clientDic;
        return clientView
    }()
    
    lazy var expressView:ExpressView = {
        let expressView:ExpressView = Bundle.main.loadNibNamed("ExpressView", owner: self, options: nil)?.first as! ExpressView
        expressView.backgroundColor = UIColor.init(hexString: "#F3F3F3")
        expressView.layer.masksToBounds = true
        expressView.layer.cornerRadius = 5
        expressView.delegate = self
        return expressView
    }()
    
    lazy var clientEmptyView:ClientEmptyView = {
        let clientEmptyView:ClientEmptyView  = Bundle.main.loadNibNamed("ClientEmptyView", owner: self, options: nil)?.first as! ClientEmptyView
        clientEmptyView.layer.masksToBounds = true
        clientEmptyView.layer.cornerRadius = 5
        clientEmptyView.delegate = self
        return clientEmptyView
    }()
    
    lazy var scrollView:UIScrollView = {
        let scrollView = UIScrollView()
        return scrollView
    }()
    
    lazy var statusBarView:UIView = {
        var height = 20
        if Constants.is_iphoneX {
            height = 40
        }
        let statusBarView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: Int(Constants.screenWidth), height:height))
        self.view.addSubview(statusBarView)
        return statusBarView
    }()
}
